[% setvar title Control flow: Builtin switch statement %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Control flow: Builtin switch statement</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Damian Conway &lt;<a href='mailto:damian@conway.org'>damian@conway.org</a>&gt;
  Date: 4 Aug 2000
  Last Modified: 18 Sep 2000
  Mailing List: <a href='mailto:perl6-language@perl.org'>perl6-language@perl.org</a>
  Number: 22
  Version: 2
  Status: Frozen</pre>
<a name='ABSTRACT'></a><h1>ABSTRACT</h1>
<p>This RFC proposes a syntax and semantics for an explicit case mechanism for
Perl. The syntax is minimal, introducing only the keywords <code>switch</code> and
<code>case</code> and conforming to the general pattern of existing Perl control
structures. The semantics are particularly rich, allowing any one (or
more) of nearly 30 forms of matching to be used when comparing a switch
value with its various cases.</p>
<a name='BACKGROUND'></a><h1>BACKGROUND</h1>
<p>In seeking to devise a &quot;Swiss Army&quot; case mechanism suitable for Perl,
it is useful to generalize the switch/case notion of distributed conditional
testing as far as possible. Specifically, the concept of &quot;matching&quot;
between the switch value and the various case values need not be
restricted to numeric (or string or referential) equality, as it is in other
languages. Indeed, as Table 1 illustrates, Perl
offers at least seventeen different ways in which two values could
generate a match.</p>
<a name='Table 1: Matching a switch value ($s) with a case value (&lt;$c&gt;)'></a><h2>Table 1: Matching a switch value (<code>$s</code>) with a case value (&lt;$c&gt;)</h2>
<pre>        Switch  Case    Type of Match Implied   Matching Code
        Value   Value   
        ======  =====   =====================   =============

        number  I&lt;same&gt; numeric or referential  C&lt;match if $s == $c;&gt;
        or ref          equality

	object  string  result of method call	&lt;match if $s-&gt;$c();&gt;
	ref     or sub
		ref

        other   other   string equality         C&lt;match if $s eq $c;&gt;
        non-ref non-ref
        scalar  scalar

        string  regexp  pattern match           C&lt;match if $s =~ /$c/;&gt;

        array   scalar  array entry existence   C&lt;match if 0E&lt;lt&gt;=$c &amp;&amp; $cE&lt;lt&gt;@$s;&gt;
        ref             array entry definition  C&lt;match if defined $s-E&lt;gt&gt;[$c];&gt;
                        array entry truth       C&lt;match if $s-E&lt;gt&gt;[$c];&gt;

        array   array   array intersection      C&lt;match if intersects(@$s, @$c);&gt;
        ref     ref     (apply this table to
                         all pairs of elements
                         C&lt;$s-E&lt;gt&gt;[$i]&gt; and
                         C&lt;$c-E&lt;gt&gt;[$j]&gt;)

        array   regexp  array grep              C&lt;match if grep /$c/, @$s;&gt;
        ref     

        hash    scalar  hash entry existence    C&lt;match if exists $s-E&lt;gt&gt;{$c};&gt;
        ref             hash entry definition   C&lt;match if defined $s-E&lt;gt&gt;{$c};&gt;
                        hash entry truth        C&lt;match if $s-E&lt;gt&gt;{$c};&gt;

        hash    regexp  hash grep               C&lt;match if grep /$c/, keys %$s;&gt;
        ref     

        sub     scalar  return value definition C&lt;match if defined $s-E&lt;gt&gt;($c);&gt;
        ref             return value truth      C&lt;match if $s-E&lt;gt&gt;($c);&gt;

        sub     array   return value definition C&lt;match if defined $s-E&lt;gt&gt;(@$c);&gt;
        ref     ref     return value truth      C&lt;match if $s-E&lt;gt&gt;(@$c);&gt;</pre>
<p>In reality, Table 1 covers 31 alternatives, because only the equality and
intersection tests are commutative; in all other cases, the roles of
the <code>$s</code> and <code>$c</code> variables could be reversed to produce a
different test. For example, instead of testing a single hash for
the existence of a series of keys (<code>match if exists $s-&gt;{$c}</code>),
one could test for the existence of a single key in a series of hashes
(<code>match if exists $c-&gt;{$s}</code>).</p>
<p>As <i><a href='http://search.cpan.org/perldoc?perltodo'>perltodo</a></i> observes, a Perl case mechanism must support all these
&quot;ways to do it&quot;.</p>
<a name='DESCRIPTION'></a><h2>DESCRIPTION</h2>
<p>Adding a switch statement would require two new control structures:
<code>switch</code> and <code>case</code>. The <code>switch</code> statement takes a single
parenthesized argument (the &quot;switch value&quot;) of any scalar type,
including any reference type. A <code>/.../</code> or <code>m{...}</code> pattern may also
be specified and is automagically converted to a <code>qr/.../</code>. A hash or array
may also be specified and is automatically enreferenced.
Regardless of the type of argument, its value is stored as the
current switch value in an inaccessible localized control variable.</p>
<p>The switch value is followed by a block, which may contain any statements,
including zero or more <code>case</code> statements.</p>
<p>The <code>case</code> statement takes a single scalar argument (which need be
parenthesized only if it's a variable), followed by a block. The <code>case</code>
statement selects the appropriate type of matching between that argument
and the current switch value, as determined by the respective types of
the switch value and the <code>case</code> argument (see Table 1). If the match is
successful, the block associated with the <code>case</code> statement is executed.</p>
<p>In most other respects, the <code>case</code> statement is semantically identical
to an <code>if</code> statement. For example, a <code>case</code> statament can be followed
by an <code>else</code> clause, and can be used as a postfix statement qualifier.</p>
<p>However, once the block of any <code>case</code> statement finishes executing,
control is immediately transferred to the end of the enclosing <code>switch</code>
statement. The same effect may be obtained by executing a <code>last</code> within
the block of the <code>switch</code>. This means that, normally, there is no C-like
&quot;fall-through&quot; from a Perl <code>case</code> statement. For example:</p>
<pre>        my $val = 7;
        switch ($val) {
                case [0..9]  { print &quot;single digit\n&quot; }
                case [10..]  { print &quot;digits\n&quot;; last }
                case 7       { print &quot;lucky seven!\n&quot; }
        }</pre>
<p>would never print &quot;lucky seven&quot;, since the first <code>case</code> will always
succeed and transfer control out of the <code>switch</code>.</p>
<p>However it <i>is</i> possible to cause a <code>case</code> statement to &quot;fall-through&quot;. If a
<code>next</code> is executed within a <code>case</code> block, control is immediately
transferred to the statement following the <code>case</code> block.
For example:</p>
<pre>        switch ($count) {
                case 0                  { print &quot;nothing\n&quot;; next }

                print &quot;fell through!\n&quot;;

                case /^\d$/             { print &quot;single\n&quot;; next }

                print &quot;fell through again!\n&quot;;

                case sub{$_[0]%2}       { print &quot;odd\n&quot; }
                else                    { print &quot;even\n&quot; }
        }</pre>
<a name='Larger examples'></a><h2>Larger examples</h2>
<pre>
        %special = ( woohoo =&gt; 1,  d'oh =&gt; 1 );

        while (&lt;&gt;) {
                switch ($_) {

                        case (%special) { print &quot;homer\n&quot;; last }       # if $special{$_}
                        case /a-z/i     { print &quot;alpha\n&quot;; last }       # if $_ =~ /a-z/i
                        case [1..9]     { print &quot;small num\n&quot;; last }   # if $_ in [1..9]

                        case sub { $_[0] &gt;= 10 } {                      # if $_ &gt;= 10
                                my $age = &lt;&gt;;
                                switch (sub { $_[0] &lt; $age } ) {

                                        case 20  { print &quot;teens\n&quot;; next }
                                        case 30  { print &quot;twenties\n&quot;; next }
                                        else     { print &quot;history\n&quot;; next }
                                }
                        }
                }

                print &quot;must be punctuation\n&quot; case /\W/;       # if $_ ~= /\W/
        }</pre>
<p>The use of intersection tests against an array reference is particularly
useful for aggregating integral cases:</p>
<pre>        sub classify_digit
        {
                switch ($_[0]) { case 0            { return 'zero' }
                                 case [2,4,6,8]    { return 'even' }
                                 case [1,3,4,7,9]  { return 'odd' }
                                 case /[A-F]/i     { return 'hex' }
			       }
        }</pre>
<a name='switch as an rvalue'></a><h2><code>switch</code> as an rvalue</h2>
<p>It is also proposed that a <code>switch</code> statement in a non-void context
might return the value of the last evaluated statement in the last
<code>case</code> or <code>else</code> it executes.</p>
<p>For example:</p>
<pre>        my $descr = switch ($num) {
                case 0            { 'zero' }
                case [2,4,6,8]    { 'even' }
                case [1,3,4,7,9]  { 'odd' }
                case /[A-F]/i     { 'hex' }
        }


        my $index = switch ($index) {
		case ^_ &lt; 0	{ $length + $index }
		case [0..9]	{ $index }
		else		{ 9 }
	}


	my %args = switch (@_) {
		case 0    { %defaults }
		case ^_%2 { warn &quot;Usage: foo(%args)&quot;; (%args, undef) }
		else	  { %args }
	}</pre>
<a name='IMPLEMENTATION'></a><h1>IMPLEMENTATION</h1>
<p>A sample (pure Perl) implementation is available on the CPAN as Switch.pm.</p>
<p>There is probably also good opportunity for compile-time optimization
for constant (or inferrable) switch/case values.</p>
<a name='REFERENCES'></a><h1>REFERENCES</h1>
<p>RFC 23 : Higher order functions</p>
<p>RFC 24 : Semi-finite (lazy) lists</p>
<p>perltodo</p>
<p>perlsyn</p>
<p>perlfaq7</p>
<p>Christiansen, T., Message posted to comp.lang.perl.misc, September 1998,
archived at <a href='http://language.perl.com/misc/fmswitch' target='_blank'>language.perl.com</a></p>
<p>Torkington, N., Message posted to perl5-porters mailing list, February 1997,
archived at
<a href='http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/1997-02/msg01558.html' target='_blank'>www.xray.mpe.mpg.de</a></p>
<p>Barr, G., Message posted to perl5-porters mailing list, October 1997,
archived at
<a href='http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/1997-10/msg00057.html' target='_blank'>www.xray.mpe.mpg.de</a></p>
</div>
